package com.book.lizhi.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.book.lizhi.AppApplication;
import com.book.lizhi.AppConfig;
import com.book.lizhi.BaseActivity;
import com.book.lizhi.R;
import com.book.lizhi.adapter.AppAdapter;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.database.DataBaseMannager;
import com.book.lizhi.http.HttpUtil;
import com.book.lizhi.http.OnHttpAsyncListener;
import com.book.lizhi.model.BookModel;
import com.book.lizhi.model.DetailBookModel;
import com.book.lizhi.util.AppLog;
import com.book.lizhi.util.Util;
import com.book.lizhi.widget.HttpPullRefreshLayout;
import com.book.lizhi.widget.MoreListView;
import com.book.lizhi.widget.MoreListView.OnMoreListener;

public class LibraryActivity extends BaseActivity {

	private MoreListView mBookListView;
	private BookAdapter mBookAdapter;
	private List<BookModel> mBookModels = new ArrayList<BookModel>();

	private HttpPullRefreshLayout mAsyncLayout;
	private TextView mTipView;

	private int mPosition = 0;
	private int mPage = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_library);

		Toolbar toolbar = (Toolbar) findViewById(R.id.toobar);
		setSupportActionBar(toolbar);

		initUI();
	}

	@Override
	protected void onResume() {
		super.onResume();

		// if (mBookModels != null && AppApplication.instance.currentBookModel != null) {
		// mBookModels.set(mPosition, AppApplication.instance.currentBookModel);
		// mBookAdapter.notifyDataSetChanged();
		// }

		if (mBookAdapter != null) {
			mBookAdapter.notifyDataSetChanged();
		}
	}

	private void initUI() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setTitle("图书");
		actionBar.setDisplayHomeAsUpEnabled(true);

		mAsyncLayout = (HttpPullRefreshLayout) findViewById(R.id.library_http_async_layout);
		mAsyncLayout.setColorSchemeResources(R.color.green);
		mBookListView = (MoreListView) findViewById(R.id.book_listView);
		mTipView = (TextView) findViewById(R.id.tip_view);
		readLocalCache();
		if (AppApplication.instance.cacheBookModels != null) {
			for (BookModel bookModel : AppApplication.instance.cacheBookModels) {
				if (AppApplication.instance.bookshelfIDs.contains(bookModel.id)) {
					bookModel.isOnBookshelf = true;
				}
			}
			mBookModels.addAll(AppApplication.instance.cacheBookModels);
		}
		mBookAdapter = new BookAdapter(this, mBookModels);
		mBookListView.setAdapter(mBookAdapter);

		addListener();

		long endTime;
		if (mBookModels != null && mBookModels.size() > 0) {
			endTime = Long.parseLong(mBookModels.get(0).time);
			endTime++;
			mAsyncLayout.setDefaultMode(true);
		} else {
			endTime = 0;
			mAsyncLayout.setDefaultMode(false);
		}
		AppLog.e("endTime:" + String.valueOf(endTime));
		sendGetRequest(HttpUtil.formateUrl(AppConfig.BOOK_HOST, String.valueOf(endTime), String.valueOf(System.currentTimeMillis())), mAsyncLayout);

	}

	private void readLocalCache() {
		String lastUrl = Util.getStringBySharePreference(Constants.LAST_REQUEST_BOOK_URL);
		AppLog.e("lasturl:" + lastUrl);
		if (!TextUtils.isEmpty(lastUrl)) {
			String cacheStr = AppApplication.instance.jsonCache.getJsonStr(lastUrl);
			AppLog.e(cacheStr);
			if (!TextUtils.isEmpty(cacheStr)) {
				AppApplication.instance.cacheBookModels = parseLocalResponse(cacheStr);
			}
		}
	}
	private List<BookModel> parseLocalResponse(String response) {
		List<BookModel> bookModels=JSON.parseArray(response, BookModel.class);
		
		for (int i=0;i<bookModels.size();i++) {
			BookModel bookModel=bookModels.get(i);
			if (AppApplication.instance.bookshelfIDs.contains(bookModel.id)) {
				bookModel.isOnBookshelf = true;
			}
		}
		return bookModels;
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.detail, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		} else if (item.getItemId() == R.id.action_bookshelf) {
			startActivity(new Intent(getApplicationContext(), NavActivity.class));
		}
		return super.onOptionsItemSelected(item);
	}

	private void addListener() {
		mAsyncLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				mAsyncLayout.bringToFront();
				long startTime = 0;
				if (mBookModels != null && mBookModels.size() > 0) {
					startTime = Long.parseLong(mBookModels.get(0).time);
					startTime++;
				}
				sendGetRequest(HttpUtil.formateUrl(AppConfig.BOOK_HOST, String.valueOf(startTime), String.valueOf(System.currentTimeMillis())), mAsyncLayout);
			}
		});
		mAsyncLayout.setOnHttpAsyncListener(new OnHttpAsyncListener() {

			@Override
			public void onHttpSuccess(boolean isCache, String url, String response) {
				List<BookModel> bookModels = parseResponse(response);
				if (!isCache && bookModels.size() > 0) {
					Util.saveDataBySharePreference(Constants.LAST_REQUEST_BOOK_URL, url);
					mBookModels.clear();
					mBookListView.reset();
					mBookModels.addAll(0, bookModels);
					mBookAdapter.notifyDataSetChanged();
					AppApplication.instance.jsonCache.saveJsonStr(url, JSON.toJSONString(mBookModels));

				}
			}

			@Override
			public void onRefresh() {
				// sendGetRequest(HttpUtil.getBookListURL(String.valueOf(mPage)), mAsyncLayout);
			}

			@Override
			public void onHttpError(VolleyError error) {
				AppLog.e("ERROR", error.toString());
				if (mBookModels.size() <= 0) {
					mTipView.setText("网络错误!!!\n\n 请稍后下拉试试!");
					mTipView.bringToFront();
				}
			}
		});

		mBookListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object object = parent.getAdapter().getItem(position);
				if (object == null && !mBookListView.isComplete() && !mBookListView.isLoading()) {

				} else if (object instanceof BookModel) {
					mPosition = position;
					AppApplication.instance.currentBookModel = (BookModel) object;
					startActivity(new Intent(getApplicationContext(), DetailActivity.class));
				}
			}
		});
		mBookListView.setMoreListener(new OnMoreListener() {

			@Override
			public void onMore(boolean isCache, String url, String response) {
				List<BookModel> bookModels;
				if (isCache) {
					bookModels = JSON.parseArray(response, BookModel.class);
					for (BookModel bookModel : bookModels) {
						if (AppApplication.instance.bookshelfIDs.contains(bookModel.id)) {
							bookModel.isOnBookshelf=true;
						}
					}
				} else {
					bookModels = parseResponse(response);
					AppApplication.instance.jsonCache.saveJsonStr(url, JSON.toJSONString(bookModels));
				}
				if (bookModels != null && bookModels.size() > 0) {
					mBookModels.addAll(bookModels);
					mBookAdapter.notifyDataSetChanged();
					mPage++;
				} else {
					mBookListView.setComplete(true);
				}
			}

			@Override
			public void onLoadMore() {
				long endTime = Long.parseLong(mBookModels.get(mBookModels.size() - 1).time);
				endTime--;
				sendGetRequest(HttpUtil.formateUrl(AppConfig.BOOK_HOST, "0", String.valueOf(endTime)), mBookListView);
			}
		});

	}

	private List<BookModel> parseResponse(String response) {
		JSONObject jsonObject = JSON.parseObject(response);
		List<BookModel> bookModels = new ArrayList<BookModel>();
		Set<String> keySet = jsonObject.keySet();
		for (String string : keySet) {
			BookModel bookModel = JSON.toJavaObject(jsonObject.getJSONObject(string), BookModel.class);
			if (AppApplication.instance.bookshelfIDs.contains(bookModel.id)) {
				bookModel.isOnBookshelf = true;
				AppLog.e("name:"+bookModel.name);
				AppLog.e("http ID:"+bookModel.id);
			}
			bookModels.add(bookModel);
		}
		Util.sortByTime(bookModels);
		return bookModels;
	}

	class BookAdapter extends AppAdapter {

		public BookAdapter(Context context, List<?> list) {
			super(context, list);
		}

		@Override
		public View getView(int position, View convertView, Context context) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(context, R.layout.book_item_layout, null);
				holder.bookCoverView = (NetworkImageView) convertView.findViewById(R.id.library_book_cover_view);
				holder.bookNameView = (TextView) convertView.findViewById(R.id.library_book_name_view);
				holder.bookAuthorView = (TextView) convertView.findViewById(R.id.library_book_author_view);
				holder.bookDesView = (TextView) convertView.findViewById(R.id.library_book_des_view);
				holder.bookAddView = (TextView) convertView.findViewById(R.id.library_book_add);
				holder.readerNUMView = (TextView) convertView.findViewById(R.id.library_book_reader);
				holder.buyView = (TextView) convertView.findViewById(R.id.library_book_buy);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final BookModel model = (BookModel) getItem(position);

			holder.bookCoverView.setDefaultImageResId(R.drawable.cover_default);
			holder.bookCoverView.setErrorImageResId(R.drawable.cover_default);
			holder.bookCoverView.setImageUrl(model.img, AppApplication.instance.imageLoader);

			holder.bookNameView.setText(model.name);
			String author = TextUtils.isEmpty(model.author) ? "佚名" : model.author;
			holder.bookAuthorView.setText(author);
			holder.bookDesView.setText(model.brief);
			if (TextUtils.isEmpty(model.readerNUM)) {
				model.readerNUM = String.valueOf(new Random().nextInt(1000));
			}
			holder.readerNUMView.setText(model.readerNUM);

			if (model.isOnBookshelf) {
				holder.bookAddView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.free_jioned, 0, 0, 0);
				holder.bookAddView.setEnabled(false);
				holder.bookAddView.setOnClickListener(null);
				holder.bookAddView.setText("已加入书架");
			} else {
				holder.bookAddView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.free_jion, 0, 0, 0);
				holder.bookAddView.setEnabled(true);
				holder.bookAddView.setText("加入书架");
				holder.bookAddView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						model.isOnBookshelf = true;

						AppApplication.instance.bookshelfIDs.add(model.id);
						DetailBookModel detailBookModel = JSON.parseObject(JSON.toJSONString(model), DetailBookModel.class);
						detailBookModel.rcIndex = String.valueOf(0);
						detailBookModel.lcIndex = String.valueOf(0);
						detailBookModel.position = String.valueOf(0);
						DataBaseMannager.getInstance().insertValue(v.getContext(), detailBookModel);

						((TextView) v).setText("已经加入书架");
						v.setEnabled(false);

						notifyDataSetChanged();
					}
				});
			}
			holder.buyView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String url = model.business;
					if (TextUtils.isEmpty(url)) {
						url = "http://s.click.taobao.com/t?e=m%3D2%26s%3DcDVusM%2BUEBkcQipKwQzePDAVflQIoZepK7Vc7tFgwiFRAdhuF14FMaAI%2FtcMbXUZ5x%2BIUlGKNpW8TUbkMajyHFRdAN7hwPSDmSDfbH0f3AiuRefWAhyyI3H5aVC8wvjy";
					}
					Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
					intent.putExtra(Constants.SOURCE_URL, url);
					intent.putExtra(Constants.TITLE, "手机淘宝网");
					LibraryActivity.this.startActivity(intent);
				}
			});
			return convertView;
		}

	}

	static class ViewHolder {
		NetworkImageView bookCoverView;
		TextView bookNameView;
		TextView bookAuthorView;
		TextView bookDesView;
		TextView bookAddView;
		TextView readerNUMView;
		TextView buyView;
	}
}
